﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace DIProject.Stock
{
    public partial class Reprice : Form
    {
        private Util.ActionType actionType;
        private Reprices reprices;
        //-------------------------------------------------------------------------------------------------
        private DIProject.DataSets.Stock repricesStock { get { return reprices != null ? reprices.stock : null; } }
        private DIProject.DataSets.StockTableAdapters.RepricesTableAdapter repricesTableAdapter { get { return reprices != null ? reprices.repricesTableAdapter : null; } }
        private DIProject.DataSets.Stock.RepricesRow repricesRow = null;
        private int docId { get { return repricesRow != null ? repricesRow.Id : 0; } }
        private string docNumber 
        { 
            get 
            { 
                return repricesRow != null ? 
                    repricesRow.DocNumber : 
                    Properties.Resources.strUndefined;
            } 
        }
        private string docDate 
        { 
            get 
            { 
                return repricesRow != null ? 
                    repricesRow.DocDate.ToString("d") : 
                    Properties.Resources.strUndefined; 
            } 
        }
        //-------------------------------------------------------------------------------------------------
        public Reprice()
            : this(Util.ActionType.NoAction, null)
        {
        }

        public Reprice(Util.ActionType actionType, Reprices reprices)
        {
            InitializeComponent();
            textFormat = Text;
            this.actionType = actionType;
            this.reprices = reprices;
            toolStripButtonUpdate.Enabled = false;
            toolStripButtonDelete.Enabled = false;
            if (actionType == DIProject.Util.ActionType.Update
            && reprices != null
            && reprices.repricesGridView.CurrentCell != null)
                repricesRow = (DIProject.DataSets.Stock.RepricesRow)((DataRowView)reprices.repricesGridView.CurrentCell.OwningRow.DataBoundItem).Row;
        }
        //-------------------------------------------------------------------------------------------------
        private readonly string textFormat;
        private void SetCaption()
        {
            Text = string.Format
            (textFormat
            , docNumber
            , docDate
            );
        }
        //-------------------------------------------------------------------------------------------------
        private void Reprice_Load(object sender, EventArgs e)
        {
            try
            {
                switch (actionType)
                {
                    case DIProject.Util.ActionType.Insert:
                        repricesRow = repricesStock.Reprices.NewRepricesRow();
                        repricesRow.DocDate = DateTime.Today;
                       // repricesRow.DocNumber = string.Empty;
                        repricesRow.MD = DateTime.Now;
                        repricesRow.MW = FirstForm.Login;
                        repricesStock.Reprices.AddRepricesRow(repricesRow);
                        goto case DIProject.Util.ActionType.Update;
                    case DIProject.Util.ActionType.Update:
                        repriceLinesTableAdapter.Fill(stock.RepriceLines, docId);
                        textBoxNote.DataBindings.Add("Text", repricesRow, "Note");
                        break;
                }
            }
            catch (SqlException eq)
            {
                MessageBox.Show(this, string.Format("{0} ({1}): {2}", eq.Procedure, eq.LineNumber, eq.Message), Properties.Resources.strError, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, Properties.Resources.strError, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            SetCaption();
        }
        //-------------------------------------------------------------------------------------------------
        private void Reprice_FormClosed(object sender, FormClosedEventArgs e)
        {
            try
            {
                if (DialogResult == DialogResult.OK)
                {
                    int delLines = stock.RepriceLines.Select(null, null, DataViewRowState.Deleted).Length
                        , insLines = stock.RepriceLines.Select(null, null, DataViewRowState.Added).Length
                        ;
                    repricesTableAdapter.Update(repricesRow);				// Заголовок документа
                    if (actionType == DIProject.Util.ActionType.Insert)
                    {
                        reprices.repricesGridView.CurrentCell = reprices.repricesGridView.Rows[reprices.repricesGridView.Rows.Count - 1].Cells[reprices.repricesGridView.CurrentCell.ColumnIndex];
                        for (int i = 0, n = stock.RepriceLines.Rows.Count; i < n; ++i)
                            stock.RepriceLines[i].DocId = repricesRow.Id;
                    }
                    repriceLinesTableAdapter.Update(stock.RepriceLines);	// Строки документа
                    repricesRow.Lines = repricesRow.Lines - delLines + insLines;

                    repricesRow.AcceptChanges();
                    stock.RepriceLines.AcceptChanges();
                }
                else
                {
                    repricesRow.RejectChanges();
                    stock.RepriceLines.RejectChanges();
                }
            }
            catch (SqlException eq)
            {
                MessageBox.Show(this, string.Format("{0} ({1}): {2}", eq.Procedure, eq.LineNumber, eq.Message), Properties.Resources.strError, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, Properties.Resources.strError, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        //-------------------------------------------------------------------------------------------------
        private void Reprice_Resize(object sender, EventArgs e)
        {
            textBoxNote.Width = panelHeader.ClientSize.Width - labelNote.Left - textBoxNote.Left;
        }
        //-------------------------------------------------------------------------------------------------
        //-------------------------------------------------------------------------------------------------
        private void contextMenuStrip1_Opening(object sender, CancelEventArgs e)
        {
            if (clickedCell != null)
            {
                updateToolStripMenuItem.Enabled = true;
                deleteToolStripMenuItem.Enabled = true;
            }
            else
            {
                updateToolStripMenuItem.Enabled = false;
                deleteToolStripMenuItem.Enabled = false;
            }
        }
        //-------------------------------------------------------------------------------------------------
        //-------------------------------------------------------------------------------------------------
        private DataGridViewCell clickedCell = null;
        private void linesGridView_MouseDown(object sender, MouseEventArgs e)
        {
            clickedCell = null;
            if (e.Button == MouseButtons.Right)
            {
                DataGridView.HitTestInfo hit = linesGridView.HitTest(e.X, e.Y);
                if (hit.Type == DataGridViewHitTestType.Cell)
                    linesGridView.CurrentCell = clickedCell = linesGridView.Rows[hit.RowIndex].Cells[hit.ColumnIndex];
            }
        }
        //-------------------------------------------------------------------------------------------------
        private void linesGridView_CurrentCellChanged(object sender, EventArgs e)
        {
            if (linesGridView.CurrentCell != null)
            {
                toolStripButtonUpdate.Enabled = true;
                toolStripButtonDelete.Enabled = true;
            }
            else
            {
                toolStripButtonUpdate.Enabled = false;
                toolStripButtonDelete.Enabled = false;
            }
        }
        //-------------------------------------------------------------------------------------------------
        //-------------------------------------------------------------------------------------------------
        private void toolStripRefresh_Click(object sender, EventArgs e)
        {
            try
            {
                repriceLinesTableAdapter.Fill(stock.RepriceLines, docId);
            }
            catch (SqlException eq)
            {
                MessageBox.Show(this, string.Format("{0} ({1}): {2}", eq.Procedure, eq.LineNumber, eq.Message), Properties.Resources.strError, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, Properties.Resources.strError, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            SetCaption();
        }
        //-------------------------------------------------------------------------------------------------
        private bool Changed()
        {
            bool changed = repricesRow.RowState != DataRowState.Unchanged
                        || DIProject.Util.Common.HasChanges(stock.RepriceLines)
                        ;
            if (changed)
            {
                if (MessageBox.Show
                (this
                , Properties.Resources.strDocIsChanged
                , Properties.Resources.strConfirmation
                , MessageBoxButtons.YesNo
                , MessageBoxIcon.Question
                , MessageBoxDefaultButton.Button1
                ) == DialogResult.Yes)
                {
                    try
                    {
                        repriceLinesTableAdapter.Update(stock);
                        changed = false;
                    }
                    catch (SqlException eq)
                    {
                        MessageBox.Show(this, string.Format("{0} ({1}): {2}", eq.Procedure, eq.LineNumber, eq.Message), Properties.Resources.strError, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(this, ex.Message, Properties.Resources.strError, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
            return changed;
        }
        //-------------------------------------------------------------------------------------------------
        private void toolStripPrint_Click(object sender, EventArgs e)
        {
            if (!Changed())
            {
                RepriceRpt repriceRpt = new RepriceRpt(docId);
                repriceRpt.ShowDialog(this);
            }
        }
        //-------------------------------------------------------------------------------------------------
        private void toolStripButtonLabels_Click(object sender, EventArgs e)
        {
            if (!Changed())
            {
                MessageBox.Show(this, "Печать этикеток и ценников", "Доделать", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
        //-------------------------------------------------------------------------------------------------
        private void toolStripInsert_Click(object sender, EventArgs e)
        {
            RepriceLine repriceLine = new RepriceLine(Util.ActionType.Insert);
            if (repriceLine.ShowDialog(this) == DialogResult.OK)
            {
                try
                {
                    DIProject.DataSets.Dictionary.PartiesRow partyRow = repriceLine.PartyRow;
                    DIProject.DataSets.Stock.RepriceLinesRow newRow = stock.RepriceLines.NewRepriceLinesRow();
                    newRow.DocId = docId;
                    newRow.OldPartyId = partyRow.Id;
                    newRow.Name = partyRow.Name;
                    newRow.ManufacturerId = partyRow.ManufacturerId;
                    newRow.ManufacturerName = partyRow.ManufacturerName;
                    newRow.NewRetailPrice = repriceLine.NewPrice;
                    newRow.OldRetailPrice = partyRow.RetailPrice;
                    newRow.Qntty = repriceLine.Qntty;
                    newRow.ReasonId = repriceLine.ReasonId;
                    newRow.ReasonName = repriceLine.ReasonName;
                    newRow.ReasonText = repriceLine.ReasonText;
                    newRow.QualityLossMark = repriceLine.QualityLossMark;
                    newRow.Note = repriceLine.Note;
                    newRow.MD = DateTime.Now;
                    newRow.MW = FirstForm.Login;
                    stock.RepriceLines.AddRepriceLinesRow(newRow);
                    linesGridView.CurrentCell = linesGridView.Rows[stock.RepriceLines.Count - 1].Cells[linesGridView.CurrentCell.ColumnIndex];
                }
                catch (SqlException eq)
                {
                    MessageBox.Show(this, string.Format("{0} ({1}): {2}", eq.Procedure, eq.LineNumber, eq.Message), Properties.Resources.strError, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(this, ex.Message, Properties.Resources.strError, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                SetCaption();
            }
        }
        //-------------------------------------------------------------------------------------------------
        private void toolStripUpdate_Click(object sender, EventArgs e)
        {
            if (linesGridView.CurrentCell != null)
            {
                try
                {
                    DIProject.DataSets.Stock.RepriceLinesRow row = (DIProject.DataSets.Stock.RepriceLinesRow)((DataRowView)linesGridView.CurrentCell.OwningRow.DataBoundItem).Row;
                    RepriceLine repriceLine = new RepriceLine(Util.ActionType.Update);
                    repriceLine.Party = row.OldPartyId;
                    repriceLine.Manufacturer = row.ManufacturerName;
                    repriceLine.Qntty = row.Qntty;
                    repriceLine.OldPrice = row.OldRetailPrice;
                    repriceLine.NewPrice = row.NewRetailPrice;
                    repriceLine.ReasonId = row.ReasonId;
                    repriceLine.ReasonText = row.ReasonText;
                    repriceLine.QualityLossMark = row.QualityLossMark;
                    repriceLine.Note = row.Note;
                    if (repriceLine.ShowDialog(this) == DialogResult.OK)
                    {
                        row.Qntty = repriceLine.Qntty;			// Меняются только количество
                        row.NewRetailPrice = repriceLine.NewPrice;			//   новая цена
                        row.ReasonId = repriceLine.ReasonId;			//   идентификатор причины
                        row.ReasonName = repriceLine.ReasonName;		//   наименование причины
                        row.ReasonText = repriceLine.ReasonText;		//   примечание к причине
                        row.QualityLossMark = repriceLine.QualityLossMark;	//   признак понижения качества
                        row.Note = repriceLine.Note;				//   и примечание
                        SetCaption();
                    }
                }
                catch (SqlException eq)
                {
                    MessageBox.Show(this, string.Format("{0} ({1}): {2}", eq.Procedure, eq.LineNumber, eq.Message), Properties.Resources.strError, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(this, ex.Message, Properties.Resources.strError, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
        //-------------------------------------------------------------------------------------------------
        private void toolStripDelete_Click(object sender, EventArgs e)
        {
            DIProject.DataSets.Stock.RepriceLinesRow rowToDelete;
            if (linesGridView.CurrentCell != null
            && (rowToDelete = (DIProject.DataSets.Stock.RepriceLinesRow)((DataRowView)linesGridView.CurrentCell.OwningRow.DataBoundItem).Row) != null
            && MessageBox.Show
                (this
                , string.Format(Properties.Resources.strDeleteDocLine, rowToDelete.Name)
                , Properties.Resources.strConfirmation
                , MessageBoxButtons.YesNo
                , MessageBoxIcon.Question
                , MessageBoxDefaultButton.Button1
                ) == DialogResult.Yes
            )
            {
                try
                {
                    rowToDelete.Delete();
                }
                catch (SqlException eq)
                {
                    rowToDelete.RejectChanges();
                    MessageBox.Show(this, string.Format("{0} ({1}): {2}", eq.Procedure, eq.LineNumber, eq.Message), Properties.Resources.strError, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                catch (Exception ex)
                {
                    rowToDelete.RejectChanges();
                    MessageBox.Show(this, ex.Message, Properties.Resources.strError, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                SetCaption();
            }
        }
        //-------------------------------------------------------------------------------------------------
        //-------------------------------------------------------------------------------------------------
        private void linesGridView_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
                e.Handled = true;
        }
        //-------------------------------------------------------------------------------------------------
        private void linesGridView_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == '\r' && linesGridView.CurrentCell != null)
                toolStripUpdate_Click(toolStripButtonUpdate, EventArgs.Empty);
        }
        //-------------------------------------------------------------------------------------------------
        private void linesGridView_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            DataGridView.HitTestInfo hit = linesGridView.HitTest(e.X, e.Y);
            if (hit.Type == DataGridViewHitTestType.Cell)
            {
                linesGridView.CurrentCell = clickedCell = linesGridView.Rows[hit.RowIndex].Cells[hit.ColumnIndex];
                toolStripUpdate_Click(toolStripButtonUpdate, EventArgs.Empty);
            }
        }
        //-------------------------------------------------------------------------------------------------
        //-------------------------------------------------------------------------------------------------
    }
}